package com.demo.component.sharding;


import io.shardingsphere.core.api.algorithm.sharding.PreciseShardingValue;
import io.shardingsphere.core.api.algorithm.sharding.standard.PreciseShardingAlgorithm;
import org.apache.commons.lang.StringUtils;

import java.util.Collection;

public final class OrderNoShardingAlgorithm implements PreciseShardingAlgorithm<String> {

    @Override
    public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<String> shardingValue) {
        //异常过滤
        if (StringUtils.isEmpty(shardingValue.getValue())) {
            throw new UnsupportedOperationException("shardingValue is null");
        }
        int valueLength = shardingValue.getValue().length();
        if (valueLength < 4) {
            throw new UnsupportedOperationException("shardingValue's length is less then 4:" + shardingValue.getValue());
        }
        //根据分片键最后两位决定路由的物理表
        String key = null;
        if ("order_no".equals(shardingValue.getColumnName())) {
            key = shardingValue.getValue().substring(valueLength - 4, valueLength - 2);
        }
        if (StringUtils.isBlank(key)) {
            throw new UnsupportedOperationException("shardingColumn is not exist: " + shardingValue.getColumnName());
        }
        String actualTable = String.format("%s_%s", shardingValue.getLogicTableName(), key);
        if (availableTargetNames.contains(actualTable)) {
            return actualTable;
        } else {
            return shardingValue.getLogicTableName();
        }
    }
}